Kurt Hsu's blog

The Rails developer in taiwan.


  • 首頁

  • 標籤

  • 分類

  • 歸檔

[Rails] FriendlyId 基本教學 操作

發表於 2018-04-17 更新於 2019-08-22 分類於 Rails , Gem

參考來源:
FriendlyId
FriendlyId完整文件

目的創造將這種網址
some_domain/products/1
變為
some_domain/products/goods1

這邊紀錄我每個步驟包括遇到的問題

步驟1: 安裝


Gemfile
1
gem 'friendly_id', '~> 5.1.0' # Note: You MUST use 5.0.0 or greater for Rails 4.0+

$ bundle install
$ rails generate friendly_id
$ rails db:migrate

步驟2: 創立表單(如果已經創立過則跳過此步驟)


FriendlyId完整文件他會教你創migration這邊用product當示範:
$ rails g model product

找到該migration

xxx_create_products.rb
1
2
3
4
5
6
7
class CreateProductLists < ActiveRecord::Migration[5.0]
def change
create_table :products do |t|
t.string :title
t.string :slug
end
end

官方補充敘述:

Temp solution for Rails 5.1+ : Before running the migration, go into the generated migration file and specify the Rails version:
class CreateFriendlyIdSlugs < ActiveRecord::Migration[5.1]
如果Rails版本超過5.1以上請修改migration第一行

$ rake db:migrate

步驟3: 實作


找到該model

app/models/products.rb
1
2
3
4
class User < ApplicationRecord
extend FriendlyId
friendly_id :title, use: :slugged
end

找到該controller

products_controller.rb
1
2
3
4
5
class UserController < ApplicationController
def show
@product = Product.friendly.find(params[:id])
end
end

如果跳過步驟2的到這肯定報錯,因為就有表單並沒有slug這個欄位,緊接著看步驟4!

步驟4: 新創表單並且更新所有表單(有操作到步驟2的則不用做步驟4)


$ rails g migration add_slug_to_product

找到該migration

add_slug_to_product.rb
1
2
3
4
5
class AddSlugToProduct < ActiveRecord::Migration[5.0]
def change
add_column :products, :slug, :string, unique: true
end
end

$ rake db:migtate
最後在終端機更新所有表單
$ rails console
$ Product.find_each(&:save)
$ exit


大功告成!

# Rails # Gem # FriendlyId
[Tool]整理程式碼 Sublime setting,BeautifyRuby, htmlbeautifier
[Rails] Boostrap Grid 用 row col 來做切版與 RWD
  • 文章目錄
  • 本站概要

Kurt Hsu

Progress One Percent Every Day
171 文章
55 分類
163 標籤
RSS
  1. 1. 步驟1: 安裝
  2. 2. 步驟2: 創立表單(如果已經創立過則跳過此步驟)
  3. 3. 步驟3: 實作
  4. 4. 步驟4: 新創表單並且更新所有表單(有操作到步驟2的則不用做步驟4)
© 2020 Kurt Hsu
由 Hexo 強力驅動 v3.8.0
|
主題 – NexT.Muse v7.3.0